package com.sdstc.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.PlanFileUtils;
import com.sdstc.modules.dao.PersonDao;
import com.sdstc.modules.dao.PersonPlanDao;
import com.sdstc.modules.dao.PlanDao;
import com.sdstc.modules.dao.PlanFileDao;
import com.sdstc.modules.eneity.PersonEntity;
import com.sdstc.modules.eneity.PersonPlanEntity;
import com.sdstc.modules.eneity.PlanEntity;
import com.sdstc.modules.eneity.PlanFileEntity;
import com.sdstc.modules.query.PlanFileQuery;
import com.sdstc.modules.service.PlanFileService;
import com.sdstc.modules.vo.PlanFileTableVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author ：wk
 * @date ：Created in 2022/11/11 9:09
 */
@Service
public class PlanFileServiceImpl implements PlanFileService {

    @Value(value = "${planFile.profile}")
    private String saveFilePath;

    @Autowired
    private PlanFileDao planFileDao;

    @Autowired
    private PlanDao planDao;

    @Autowired
    private PersonDao personDao;

    @Autowired
    private PersonPlanDao personPlanDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PlanFileEntity savePlanFile(PlanFileEntity planFileEntity, MultipartFile file){

        String savePath = saveFilePath + "/" + planFileEntity.getTempVersionId();


        planFileEntity.setFilePath(savePath + "/" + file.getOriginalFilename());

        planFileDao.insert(planFileEntity);

        PlanFileUtils.uploadFile(file,savePath,file.getOriginalFilename());

        return planFileEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PlanFileEntity updatePlanFile(PlanFileEntity planFileEntity){
        planFileDao.updateById(planFileEntity);
        return planFileEntity;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePlanFile(String fileId){
        planFileDao.deleteById(fileId);
    }

    @Override
    public List<PlanFileEntity> getPlanFileList(PlanFileQuery planFileQuery){
        if (StringUtils.isBlank(planFileQuery.getTempVersionId()) && StringUtils.isBlank(planFileQuery.getPlanId())){
            return new ArrayList<>();
        }
        return planFileDao.selectList(new QueryWrapper<PlanFileEntity>()
                .like(StringUtils.isNotBlank(planFileQuery.getFileName()), "file_name" ,planFileQuery.getFileName())
                .eq(StringUtils.isNotBlank(planFileQuery.getTempVersionId()), "temp_version_id", planFileQuery.getTempVersionId())
                .eq(StringUtils.isNotBlank(planFileQuery.getPlanId()), "plan_id", planFileQuery.getPlanId())
                .eq(StringUtils.isNotBlank(planFileQuery.getFileType()), "file_type", planFileQuery.getFileType()));
    }


    @Override
    public PlanFileTableVo getPlanFilePage(PlanFileQuery planFileQuery){
        PlanFileTableVo planFileTableVo = new PlanFileTableVo();
        String startTime = CollectionUtils.isNotEmpty(planFileQuery.getQueryTime()) ? planFileQuery.getQueryTime().get(0) : null;
        String endTime = CollectionUtils.isNotEmpty(planFileQuery.getQueryTime()) ? planFileQuery.getQueryTime().get(1) : null;
        List<PlanFileEntity> result = planFileDao.selectList(new QueryWrapper<PlanFileEntity>()
                .or().like(StringUtils.isNotBlank(planFileQuery.getQueryParam()), "file_name", planFileQuery.getQueryParam())
                .or().eq(StringUtils.isNotBlank(planFileQuery.getQueryParam()),"approval_no",planFileQuery.getQueryParam())
                .or().like(StringUtils.isNotBlank(planFileQuery.getQueryParam()), "approval_office",planFileQuery.getQueryParam())
                .or().like(StringUtils.isNotBlank(planFileQuery.getQueryParam()), "determine_thing", planFileQuery.getQueryParam())
                .or().eq(StringUtils.isNotBlank(planFileQuery.getQueryParam()), "temp_version_id", planFileQuery.getQueryParam())
                .or().eq(StringUtils.isNotBlank(planFileQuery.getQueryParam()), "plan_id", planFileQuery.getQueryParam())
                .or().eq(StringUtils.isNotBlank(planFileQuery.getQueryParam()), "file_type", planFileQuery.getQueryParam())
                .apply(StringUtils.isNotBlank(startTime),"date_format (send_time,'%Y-%m-%d') >= date_format({0},'%Y-%m-%d')",startTime)
                .apply(StringUtils.isNotBlank(endTime),"date_format (send_time,'%Y-%m-%d') <= date_format({0},'%Y-%m-%d')",endTime));
//                .eq(Objects.nonNull(planFileQuery.getSendTime()), "send_time", planFileQuery.getSendTime()));
        List<String> planIdList = planDao.selectList(new QueryWrapper<PlanEntity>().eq("status", "1"))
                .stream().map(PlanEntity::getId).collect(Collectors.toList());
        result = result.stream().filter(p -> planIdList.contains(p.getPlanId())).collect(Collectors.toList());
        List<String> planIds = new ArrayList<>();

        if (StringUtils.isNotBlank(planFileQuery.getQueryParam())){
            // 根据调整人员姓名查询处人员id
            List<String> personIds = personDao.selectList(new QueryWrapper<PersonEntity>().like("name", planFileQuery.getQueryParam()))
                    .stream().map(PersonEntity::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(personIds)){
                // 根据人员id查询处planId
                planIds = new ArrayList<>(personPlanDao.selectList(new QueryWrapper<PersonPlanEntity>().in("person_id", personIds))
                        .stream().collect(Collectors.groupingBy(PersonPlanEntity::getPlanId)).keySet());
            }
        }

        if (CollectionUtils.isNotEmpty(planIds)){
            List<String> finalPlanIds = planIds;
            for (String planId : finalPlanIds) {
                List<PlanFileEntity> planFile = planFileDao.selectList(new QueryWrapper<PlanFileEntity>().eq("plan_id", planId));
                result.addAll(planFile);
            }
//            result = result.stream().filter(p -> finalPlanIds.contains(p.getPlanId())).collect(Collectors.toList());
        }

        planFileTableVo.setTotal(result.size());

        result = result.stream().skip((long) (planFileQuery.getPageNum() - 1) * planFileQuery.getPageSize()).limit(planFileQuery.getPageSize()).
                collect(Collectors.toList());

        planFileTableVo.setRows(result);

        return planFileTableVo;
    }

}
